﻿// ———————————————————————–
// <copyright file="ExceptionService.cs" company="The MITRE Corporation">
//    Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// ———————————————————————–
/////////////////////////////////////////////////////////////////////////////////////////////////
// ExceptionService.cs - Handles And Logs Exceptions
// Project: "ICNETSOA"- "ExceptionService"
//
// Language:    C#, .NET 4.0
// Platform:    Windows 7, VS 2010
// Author:      Don McGarry The MITRE Corporation
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)
                
using System;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using EDXLSharp;
using EDXLSharp.EDXLDELib;
using ICNETServices;
using System.IO;

namespace ExceptionSvc
{
  /// <summary>
  /// Contians methods for handling exceptions in DE messages.
  /// </summary>
  public class ExceptionService : IRoutingICNET
  {
    /// <summary>
    /// The output directory where the logs are stored.
    /// </summary>
    private static string outputdir = ICNETSOAConstants.ICNETInstallPath + @"ErrorLog";

    /// <summary>
    /// Processes a DE and logs any exceptions thta have occureed. 
    /// </summary>
    /// <param name="distributionElementObject">A DE to be processed. </param>
    [OperationBehavior(TransactionAutoComplete = true)]
    public void ProcessDE(EDXLDE distributionElementObject)
    {
      XElement xe = new XElement("Test");
      foreach (ContentObject co in distributionElementObject.ContentObjects)
      {
        foreach (ValueList list in co.ContentKeyword)
        {
          if (list.ValueListURN == ICNETSOAConstants.ICNETExceptionURI)
          {
            if (co.XMLContent != null)
            {
              xe.Add(co.XMLContent.EmbeddedXMLContent.First());
            }
            else if (co.NonXMLContent != null)
            {
              xe.Add("StringData", new XCData(Encoding.ASCII.GetString(Convert.FromBase64String(co.NonXMLContent.ContentData))));
            }
          }
        }
      }



     
      string errorLogDir = outputdir;
      if (!Directory.Exists(errorLogDir))
      {
          Directory.CreateDirectory(errorLogDir);
      }

      string errorTimestampDir = errorLogDir+"\\"+DateTime.Now.ToLocalTime().ToString("MM-dd-yyyy");
      if (!Directory.Exists(errorTimestampDir))
      {
          Directory.CreateDirectory(errorTimestampDir);
      }

      string errorFilename;
      if (String.IsNullOrEmpty(distributionElementObject.SenderID) || String.IsNullOrEmpty(distributionElementObject.DistributionID))
      {
          errorFilename = Guid.NewGuid().ToString(); // no usable identifier in the EDXL message, so just use a GUID as the filename
      }
      else
      {
          errorFilename = distributionElementObject.SenderID + " - " + distributionElementObject.DistributionID + " - " + Guid.NewGuid().ToString();
          errorFilename = errorFilename.Replace(":", ","); // remove unusable characters
      }


      XmlWriter xw = XmlWriter.Create(errorTimestampDir + "\\" + errorFilename + ".xml");
      xw.WriteStartElement("Error");
      XElement xe2 = XElement.Parse(distributionElementObject.WriteToXML());
      xe2.WriteTo(xw);
      xe.WriteTo(xw);
      xw.Flush();
      xw.Close();
    }
  }
}
